//
//  HMEmoticonKeyBoard.swift
//  MicroBlog
//
//  Created by Apple on 16/10/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//自定义表情键盘视图
//1.表情视图 -> UICollectionView
//2.页数指示器 -> UIPageControl
//3.toolBar -> UIStackView

//重用标记
private let HMEmoticonCollectionViewCellIdentifier = "cell"
class HMEmoticonKeyBoard: UIView {

    //页数指示器
    fileprivate lazy var pageControl: UIPageControl = {
        let ctr = UIPageControl()
        //当前选中的颜色
        ctr.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        //默认页数的颜色
        ctr.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        //隐藏单页
        ctr.hidesForSinglePage = true
        return ctr
    }()
    
    //toolBar
    fileprivate lazy var toolBar: HMEmoticonToolBar = HMEmoticonToolBar()
    //表情视图
    fileprivate lazy var emoticonCollecionView: UICollectionView = {
       let flowLayout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        view.backgroundColor = self.backgroundColor
        //滚动方向
        flowLayout.scrollDirection = .horizontal
        //开启分页
        view.isPagingEnabled = true
        //隐藏滚动条
        view.showsHorizontalScrollIndicator = false
        //去掉弹簧效果
        view.bounces = false
        //注册
        view.register(HMEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: HMEmoticonCollectionViewCellIdentifier)
        //数据源
        view.dataSource = self
        //代理
        view.delegate = self
        return view
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //设置背景颜色
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        //设置滚动到的indexPath
        let normalIndexPath = IndexPath(item: 0, section: 1)
        //主线程异步,等待其他视图初始化完成和绑定数据完成后,才滚动到默认表情数组
        DispatchQueue.main.async {
            //默认滚动到这组表情数据
            self.emoticonCollecionView.scrollToItem(at: normalIndexPath, at: .left, animated: false)
        }
        //获取默认Page的数据
        self.setPageControlData(indexPath: normalIndexPath)
        
        addSubview(emoticonCollecionView)
        addSubview(toolBar)
        addSubview(pageControl)
        
        emoticonCollecionView.snp_makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pageControl.snp_makeConstraints { (make) in
            make.bottom.centerX.equalTo(emoticonCollecionView)
            make.height.equalTo(10)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(self)
            make.height.equalTo(35)
        }
        //循环引用,使用[weak self]
        toolBar.callBack = { [weak self] (type: HMEmoticonToolBarButtonType) in
            let indexPath: IndexPath
            switch type {
            case .recent:
                print("最近")
                indexPath = IndexPath(item: 0, section: 0)
            case .normal:
                print("默认")
                indexPath = IndexPath(item: 0, section: 1)
            case .emoji:
                print("emoji")
                indexPath = IndexPath(item: 0, section: 2)
            case .lxh:
                print("浪小花")
                indexPath = IndexPath(item: 0, section: 3)
            }
            //把collectionView滚动到指定的indexPath上
            //不需要开启动画
            self?.emoticonCollecionView.scrollToItem(at: indexPath, at: .left, animated: false)
            
            self?.setPageControlData(indexPath: indexPath)
        }
    }
    
    //设置表情视图条目的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        //获取布局方式
        let flowLayout = emoticonCollecionView.collectionViewLayout as! UICollectionViewFlowLayout
        //条目大小
        flowLayout.itemSize = emoticonCollecionView.size
        //垂直间距
        flowLayout.minimumLineSpacing = 0
        //水平间距
        flowLayout.minimumInteritemSpacing = 0
    }
    
    //通过IndexPath绑定pageControl数据
    func setPageControlData(indexPath: IndexPath) {
        pageControl.numberOfPages = HMEmoticonTools.shareTools.allEmoticonsArray[indexPath.section].count
        pageControl.currentPage = indexPath.item
    }
    
    //刷新最近表情数据
    func reloadRecentData() {
        emoticonCollecionView.reloadItems(at: [IndexPath(item: 0, section: 0)])
    }
}

extension HMEmoticonKeyBoard: UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonTools.shareTools.allEmoticonsArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonTools.shareTools.allEmoticonsArray[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMEmoticonCollectionViewCellIdentifier, for: indexPath) as! HMEmoticonCollectionViewCell
        cell.emoticonsArray = HMEmoticonTools.shareTools.allEmoticonsArray[indexPath.section][indexPath.item]
        return cell
    }
    //监听collectionView的滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取表情视图的中心点
        let centerX = scrollView.contentOffset.x + emoticonCollecionView.width / 2
        let centerY = scrollView.contentOffset.y + emoticonCollecionView.height / 2
        //方式二:通过坐标的转换:emoticonCollecionView在HMEmoticonKeyBoard上的中心点转换成表情视图(emoticonCollecionView)的中心点
//        let pointtInView =  self.convert(emoticonCollecionView.center, to: emoticonCollecionView)
        let center = CGPoint(x: centerX, y: centerY)
        //通过中心点获取对应cell的indexPath
        if let indexPath = emoticonCollecionView.indexPathForItem(at: center) {
            //获取对应的section
            let section = indexPath.section
            //传入组号
            toolBar.selectedButton(section: section)
            setPageControlData(indexPath: indexPath)
        }
       
    }
    
}
